package com.scc.datastructrues.链表;



@SuppressWarnings("unchecked")
public class ArrayList<E> extends AbstractList<E>{
	
	private E[] elements;
	
	private static final int DEFAULT_CAPACITY = 10;
	
	public ArrayList() {
		this(DEFAULT_CAPACITY);
	}
	
	public ArrayList(int capacity) {
		capacity = capacity < DEFAULT_CAPACITY ? DEFAULT_CAPACITY : capacity;
		elements = (E[])new Object[capacity];
	}


	public void clear() {
		for (int i = 0; i < size; i++) {
			elements[i] = null;
		}
		size = 0;
	}
	
	
	
	public E get(int index) {
		rangeCheck(index);
		return elements[index];
	}
	
	/**设置index位置的元素
	 * @param index
	 * @param element
	 * @return 原来的元素
	 */
	public E set(int index,E element) {
		rangeCheck(index);
		E oldElement = elements[index];
		elements[index] = element;
		return oldElement;
	}
	
	/**在index位置插入一个元素
	 * @param index
	 * @param element
	 */
	public void add(int index,E element) {
		rangeCheckForAdd(index);
		ensureCapacity(size + 1);
		// index及以后的后移
//		for (int i = size - 1; i >= index; i--) {
//			elements[i + 1] = elements[i];
//		}
		
		// 比上面优化
		for (int i = size; i > index; i--) {
			elements[i] = elements[i - 1];
		}
		
		elements[index] = element;
		size++;
	}
	
	/**删除index位置的元素
	 * @param index
	 * @return 被删除的元素
	 */
	public E remove(int index) {
		rangeCheck(index);
		E oldElement = elements[index];
		for (int i = index + 1; i < size; i++) {
			elements[i - 1] = elements[i];
		}
		elements[--size] = null;
		return oldElement;
	}
	
	/**查看元素的索引
	 * @param element
	 * @return
	 */
	public int indexOf(E element) {
		if (element == null) {
			for (int i = 0; i < elements.length; i++) {
				if (elements[i] == null) return i;
			}
		}else {
			for (int i = 0; i < elements.length; i++) {
				if (element.equals(elements[i])) return i;
			}
		}
	
		return ELEMENT_NOT_FOUND;
	}
	
	private void ensureCapacity (int capacity) {
		int oldCapacity = elements.length;
		if (oldCapacity >= capacity) return;
		int newCapacity = oldCapacity + oldCapacity >> 1; 
		E[] newArrEs = (E[]) new Object[newCapacity];
		for (int i = 0; i < size; i++) {
			newArrEs[i] = elements[i];
		}
		elements = newArrEs;
		
		System.out.println(oldCapacity + "扩容为" + newCapacity);
	}
	
	
	@Override
	public String toString() {
		// size = 3, [99, 88, 77]
		StringBuffer string = new StringBuffer("size = " + size + ", [");
		for (int i = 0; i < size; i++) {
			E e = elements[i];
			if(i != 0) string.append(", ");
			string.append(e.toString());
		}
		string.append("]");
		return string.toString();
	}
	
	
	
	

	
	
	
	
	
	
	

}
